// 引入接口文件
import { editFun, addFun, queryInfo, getFirst, updatepriceRatioReason } from './groupWeekReportDetailServ.js'

// 对象和JSON字符串互转
import { parse } from 'qs'
// 弹出消息框
import { message } from 'antd'
// 日期处理对象
import moment from 'moment'
import { rstr2b64 } from '../../../../utils/md5'
/* isEmpty 对象是否为空
 * isArray 对象是否数组
 * cloneDeep 对象深拷贝
 */
import { isEmpty, isArray, cloneDeep, merge } from 'lodash'
// 引入路由对象
import { hashHistory } from 'dva/router'

// 初始默认状态
const defultState = {
  btnLoading: false,
  loading: false,
  isShow: true,
  actionType: 'add',
  weekInitType: true,
  competitorOpeningQuotationList: [],
  competitorOpeningCount: 0,
  query: {
    id: '',
    startTime: '',
    endTime: '',
    title: '',
    createBy: '',
    createTime: "",
    status: "",
    updateBy: "",
    updateTime: "",
    data: {
      conclusion: '',
      citycount: '',
      competcount: '',
      procount: '',
      fivePointConut: '',
      setProjectCount: '',
      weeklyLand: [], //土拍
      weeklyPolicy: [], //政策
      weeklyCompeting: [], //竞品
      weeklyInfo: [],
      competitorOpeningQuotationList: [],//开盘竞品
      competitorOpeningQuotationCount: 0,
    },
  }
}

// 声明module
const tmpModule = {
  namespace: 'defaultModel',
  // 默认状态
  state: cloneDeep(defultState),
  // 入口函数(先执行)
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname, query }) => {
        // 页面路由匹配时执行
        if ('' + tmpModule.pathname === '' + pathname) {
          // 执行业务操作
          dispatch({ type: 'updateStore', payload: { ...cloneDeep(defultState), ...query } })//每次进去页面先重置状态
          if (query.actionType == 'check' || query.actionType == 'edit') {
            dispatch({ type: 'queryInfo', payload: { id: query.id } })
          }
        } // end if
      }) // end listen
    },
  },

  // 方法列表
  effects: {
    // 查询记录
    *queryInfo({ payload }, { put, select, call }) {
      let { query, competitorOpeningQuotationList, competitorOpeningCount } = yield select(state => state[tmpModule.namespace])
      let params = {
        id: payload.id,
      }
      const { success, result } = yield call(queryInfo, { ...params })
      if (success) {
        result.data = JSON.parse(result.data)
        competitorOpeningQuotationList = result.data.competitorOpeningQuotationList;
        competitorOpeningCount = result.data.competitorOpeningQuotationCount;
        if (result.data.weeklyInfo.length > 0) {
          let citycountAll = 0;
          let procountAll = 0;
          let competcountAll = 0;
          result.data.weeklyInfo.forEach(({ citycount, procount, competcount }) => {
            citycountAll += parseFloat(citycount);
            procountAll += parseFloat(procount);
            competcountAll += parseFloat(competcount);
          });
          citycountAll = Math.round(parseFloat(citycountAll) * 100) / 100
          procountAll = Math.round(parseFloat(procountAll) * 100) / 100
          competcountAll = Math.round(parseFloat(competcountAll) * 100) / 100
          let obj = {
            citycount: citycountAll,
            procount: procountAll,
            competcount: competcountAll,
            area: '合计',
          }
          result.data.weeklyInfo.push(obj)
        }
        query = result
        yield put({
          type: 'updateStore',
          payload: { query, competitorOpeningQuotationList, competitorOpeningCount }
        })
      }
    },
    // 初始化
    *getFirst({ payload }, { put, select, call }) {
      let { query, actionType, weekInitType, competitorOpeningQuotationList, competitorOpeningCount } = yield select(state => state[tmpModule.namespace])
      if (!query.startTime || !query.endTime) {
        message.warning('请先选择时间')
        return
      }
      let params = {
        startTime: query.startTime,
        endTime: query.endTime,
        status: actionType == 'add' ? '1' : '2'
      }
      const {
        success, weeklyCompeting, weeklyLand,
        weeklyPolicy, weeklyInfo, citycount, competcount,
        procount, fivePointConut, setProjectCount,
        competitorOpeningQuotation, competitorOpeningQuotationCount } = yield call(getFirst, { ...params })
      weekInitType = success
      yield put({ type: 'updateStore', payload: { weekInitType } })
      if (success) {
        competitorOpeningQuotationList = [];
        let newArr = [];
        let str = '';
        let i = 0;
        for (let item of competitorOpeningQuotation) {
          if (str.indexOf(item.competingGoodsId) < 0) {
            let arr = [];
            str += `${item.competingGoodsId},`;
            for (let child of competitorOpeningQuotation) {
              if (child.competingGoodsId == item.competingGoodsId) {
                arr.push(child)
              }
            }
            arr = arr.sort((a, b) => { return a.sort - b.sort });
            newArr.push(arr);
          }
        }
        for (let item of newArr) {
          for (let child of item) {
            child.parentCode = child.competingGoodsId + child.parentCode;
            competitorOpeningQuotationList.push(child);
          }
        }
        for (let item of competitorOpeningQuotationList) {
          if (item.ourProjects) {
            let arr = item.ourProjects.split(",");
            let str = '';
            for (let child of arr) {
              if (str) {
                str += ('、' + child.split(":")[1])
              } else {
                str += child.split(":")[1];
              }
            }
            item.ourProjects = str;
          }
        };
        competitorOpeningCount = competitorOpeningQuotationCount;
        query.data.weeklyCompeting = weeklyCompeting
        query.data.weeklyLand = weeklyLand
        query.data.weeklyPolicy = weeklyPolicy
        query.data.weeklyInfo = weeklyInfo
        query.data.citycount = citycount
        query.data.competcount = competcount
        query.data.procount = procount
        query.data.fivePointConut = fivePointConut
        query.data.setProjectCount = setProjectCount

        if (weeklyInfo.length > 0) {
          let citycountAll = 0;
          let procountAll = 0;
          let competcountAll = 0;
          weeklyInfo.forEach(({ citycount, procount, competcount }) => {
            citycountAll += parseFloat(citycount);
            procountAll += parseFloat(procount);
            competcountAll += parseFloat(competcount);
          });
          citycountAll = Math.round(parseFloat(citycountAll) * 100) / 100
          procountAll = Math.round(parseFloat(procountAll) * 100) / 100
          competcountAll = Math.round(parseFloat(competcountAll) * 100) / 100
          let obj = {
            citycount: citycountAll,
            procount: procountAll,
            competcount: competcountAll,
            area: '合计',
          }
          query.data.weeklyInfo.push(obj)
        }
        yield put({
          type: 'updateStore',
          payload: { query, competitorOpeningQuotationList, competitorOpeningCount }
        })
      }
    },
    *submit({ payload }, { put, select, call }) {
      let { loading, btnLoading, query, actionType, competitorOpeningQuotationList, competitorOpeningCount } = yield select(state => state[tmpModule.namespace])
      if (payload.type == '保存') {
        query.status = '0'
        btnLoading = true
        yield put({ type: 'updateStore', payload: { btnLoading } })
      }
      if (payload.type == '提交') {
        query.status = '1'
        loading = true
        yield put({ type: 'updateStore', payload: { loading } })
      }
      query.createBy = localStorage.nickname
      query.createUser = localStorage.username
      query.data.competitorOpeningQuotationList = competitorOpeningQuotationList;
      query.data.competitorOpeningQuotationCount = competitorOpeningCount;
      query.data.weeklyInfo = query.data.weeklyInfo.filter(item => item.area != '合计')
      query.data = JSON.stringify(query.data)
      let params = query

      if (actionType == 'add') {
        let { success, msg, data } = yield call(addFun, { ...params })
        let flag = success.toString()
        if (flag) {
          if (payload.type == '保存') {
            btnLoading = false
            yield put({ type: 'updateStore', payload: { btnLoading } })
          }
          if (payload.type == '提交') {
            loading = false
            yield put({ type: 'updateStore', payload: { loading } })
          }
        }
        if (success) {
          message.success(payload.type == '保存' ? '保存成功' : '提交成功')
          hashHistory.push({
            pathname: '/home/predictManage/weekReport',
            query: { tabsType: '2' }
          })
        }
      }
      if (actionType == 'edit') {
        let { success, msg, data } = yield call(editFun, { ...params })
        let flag = success.toString()
        if (flag) {
          if (payload.type == '保存') {
            btnLoading = false
            yield put({ type: 'updateStore', payload: { btnLoading } })
          }
          if (payload.type == '提交') {
            loading = false
            yield put({ type: 'updateStore', payload: { loading } })
          }
        }
        if (success) {
          message.success(payload.type == '保存' ? '保存成功' : '提交成功')
          hashHistory.push({
            pathname: '/home/predictManage/weekReport',
            query: { tabsType: '2' }
          })
        }
      }
    },
    *updatepriceRatioReason({ payload }, { put, select, call }) {
      let { isShow } = yield select(state => state[tmpModule.namespace])
      let params = {
        id: payload.id,
        reason: payload.reason
      }
      let { success, msg, data } = yield call(updatepriceRatioReason, { ...params })
      if (success) {
        message.success('保存成功')
        isShow = true
        yield put({
          type: 'updateStore',
          payload: { isShow }
        })
      }
    }
  },

  // 存入状态机
  reducers: {
    updateStore(preState, action) {
      return Object.assign({}, preState, action.payload)
    },
  }
}

export default tmpModule
